<template>
  <div @mousedown.prevent="drag" style="padding: 20px 0" ref="sliderWrapper">
    <div class="slider_runway">
      <div class="slider_bar" :style="barWidth"></div>
      <div class="slider_button_wrapper" :style="translate">
        <div :class="['slider_button', { dragging: isClick }]"></div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  model: {
    prop: 'value',
    event: 'parent-event'
  },
  props: {
    value: Number
  },
  data () {
    return {
      w: 0,
      translate: '',
      barWidth: '',
      isClick: false
    }
  },
  mounted () {
    // 获取外框的宽度作为基值
    this.w = this.$refs.sliderWrapper.offsetWidth
    // 通过父组件传来的百分比值设置进度的位置
    this.move(this.value)
  },
  methods: {
    move (value) {
      if (value >= 0 && value < this.w) { // 设置边界防止滑动出轨
        this.$emit('parent-event', value)// 将修改后的百分比值传给父组件
        this.barWidth = `width:${value}%`
        this.translate = `transform:translateX(${value / 100 * this.w}px)`
      }
    },
    drag ({ clientX }) { // 点击后调用 move 和 up 事件
      this.isClick = true// 点击圆点时候会鼠标会改变
      this.move(clientX / this.w * 100) // 点击轨道我们也要让他移动
      document.onmousemove = e => { // 拖动圆点进行移动
        e.preventDefault()// 取消默认事件 否则会把莫名的东西拽走
        this.move(e.clientX / this.w * 100)
      }
      document.onmouseup = e => { // 必须在抬起鼠标时候清除move 和 up事件，否则会不停的 move下去
        e.preventDefault() // 虽然不会影响什么，但是还是把它给取消了吧
        this.isClick = false
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
}
</script>
<style scoped>
.slider_runway {
  position: relative;
  width: 100%;
  height: 4px;
  background: rgba(230, 230, 230, 0.3);
  cursor: pointer;
}
.slider_bar {
  width: 0%;
  height: 4px;
  background: #000000;
}
.slider_button_wrapper {
  position: absolute;
  top: -5px;
  width: 14px;
  height: 14px;
}
.slider_button {
  position: absolute;
  width: 14px;
  height: 14px;
  top: 0;
  left: -14px;
  cursor: grab;
  background: #ffffff;
  border-radius: 50%;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.23);
  transform: scale(1);
  transition: 0.2s;
}
.dragging {
  cursor: grabbing;
}
.slider_button:hover {
  transform: scale(1.2);
}
</style>
